<!-- 组织选择 -->
<template>
	<el-tree-select
		size="default"
		v-model="value"
		:data="orgList"
		node-key="id"
		:props="{
			label: 'deptName',
			value: 'deptId',
			children: 'children',
		}"
		:show-checkbox="false"
		:default-expand-all="props.expandAll"
		:expand-on-click-node="false"
		:check-strictly="true"
		@node-click="onChange"
		style="width: 170px"
		:disabled="deptId != 100"
	>
	</el-tree-select>
</template>

<script lang="ts" setup name="orgSelect">
import { onMounted, ref, toRaw } from 'vue';
import { storeToRefs } from 'pinia';
import { getDeptTree } from '/@/api/system/user/index';
import { useUserInfo } from '/@/stores/userInfo';
const stores = useUserInfo();

const { userInfos, roleIds, communitys } = storeToRefs(stores);

const props = defineProps({
	deptId: {
		type: [String, Number],
		default: '',
	},
	noData: {
		type: Array,
		default: () => {
			return [];
		},
	},
	expandAll: {
		type: Boolean,
		default: true,
	},
});

const value = ref(props.deptId || '');
const orgList: any = ref([]);

defineExpose({});
// emit

const emit = defineEmits(['selected', 'orgSeleced']);

// 刷新
async function getOrgList() {
	getDeptTree().then((res: any) => {
		res.data.deps[0].children = res.data.deps[0].children.filter((item: any) => {
			return !['安装人员', '其它', '测试'].includes(item.deptName);
		});

		// 通过角色判断是否展示全部组织
		let flag = false;
		let canUseAll = [1, 2, 5];
		roleIds.value.forEach((element) => {
			if (canUseAll.includes(element)) {
				flag = true;
			}
		});

		if (flag) {
			orgList.value = res.data.deps;
		} else {
			treeForeach(res.data.deps, d);
		}
	});
}

function treeForeach(tree: any, func: any) {
	tree.forEach((data: any) => {
		func(data);
		data.children && treeForeach(data.children, func); // 遍历子树
	});
}

function d(item: any) {
	if (item.deptId == props.deptId) {
		orgList.value = [item];
	}
}

function getTreeIds(treeIds: number[], item: any[]) {
	item.forEach((element) => {
		treeIds.push(element.deptId);
		element.children && getTreeIds(treeIds, element.children);
	});
}

function onChange(e: any) {
	if (e.deptId == 100) {
		emit('orgSeleced');
		return;
	}

	// const ids = e.children ? e.children.map((item: any) => item.deptId) : [];
	let arr = [toRaw(e)];
	let treeIds: number[] = [];
	getTreeIds(treeIds, arr);
	emit('selected', { ids: treeIds, dept: e });
}

onMounted(() => {
	getOrgList();
});
</script>
